<?php

namespace App\Http\Controllers\Front;

use App\Models\Goods;
use App\Models\Order;
use App\Models\OrderGoods;
use App\Services\Allinpay\Refund;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Interfaces\RefundGoodsService;
use App\Interfaces\RefundGoodsOperationRecordService;
use App\Models\RefundGoods;
use App\Models\RefundGoodsOperationRecord;
use Auth;
use App\Exceptions\Interfaces\RefundGoodsServiceException;
use App\Http\Requests\Front\my\RefundGoodsApplyRequest;
use App\Commands\OperationLogCommand;
use Log;

class MyRefundGoodsController extends Controller
{
    private $user_id;
    public function __construct()
    {

        $this->user_id = @Auth::user()->id;
        //$this->user_id = 198859;
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        //return view('front.my.refund_goods_detail');         //商品退货明细列表
        /*$orders = Order::select('order.order_sn','order.shop_id', 'order_goods.*')
                ->leftJoin('order_goods', 'order_goods.order_id', '=', 'order.order_id')
                ->paginate(10);         //结果没有软删除的订单*/

        $query = Order::orderBy('add_time', 'desc')
                ->where('user_id', $this->user_id)
                ->where('order_status', 4);

        $search = array('order_sn'=>'');

        if ($request->get('order_sn')!=''){
            $query = $query->where('order_sn', $request->get('order_sn'));
            $search['order_sn'] = $request->order_sn;
        }//end if()

        $orders = $query->paginate(10);         //结果没有软删除的订单


        return view('front.my.refund_goods_apply_list', compact(['orders', 'search']));         //商品退货申请
        //return view('front.my.refund_goods_record');         //商品退货记录
        //return view('front.my.refund_goods_record2');         //商品退款明细
    }

    /**
     * 创建售后单
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    // public function create(RefundGoodsService $refundGoodsService, RefundGoodsOperationRecordService $refundGoodsOperationRecordService, RefundGoodsApplyRequest $request)
    public function create(RefundGoodsService $refundGoodsService, RefundGoodsOperationRecordService $refundGoodsOperationRecordService, Request $request)
    {

        $return = ['status'=>1, 'message'=>'', 'data'=>''];

        $after_sales_type = $request->after_sales_type;     //售后类型

        $after_sales_number = $request->after_sales_number; //售后数量

        $reason = $request->reason;                         //售后（退/换货）原因

        $real_name = $request->consignee;                   //收货人

        $phone = $request->phone;                           //手机号码

        $order_sn = $request->order_sn;                     //订单编号

        $goods_id = $request->goods_id;                     //商品id

        $user_id = $this->user_id;

        $remark = '';           //备注信息

        if(empty($after_sales_type)){

            $return['status'] = 0;

            $return['message'] = "售后类型不能为空";

            return $return;
        }//end if()

        if(empty($after_sales_number) || $after_sales_number<=0){

            $return['status'] = 0;

            $return['message'] = "数量不能为空且不能小于0";

            return $return;
        }//end if()

        if(empty($reason)){

            $return['status'] = 0;

            $return['message'] = "原因不能为空";

            return $return;
        }//end if()

        if(empty($real_name)){

            $return['status'] = 0;

            $return['message'] = "收货人不能为空";

            return $return;
        }//end if()

        if(empty($phone)){

            $return['status'] = 0;

            $return['message'] = "手机号码不能为空";

            return $return;
        }//end if()

        if(empty($order_sn)){

            $return['status'] = 0;

            $return['message'] = "订单编号不能为空";

            return $return;
        }//end if()

        if(empty($goods_id)){

            $return['status'] = 0;

            $return['message'] = "商品id不能为空";

            return $return;
        }//end if()

        $isHas = RefundGoods::where('order_sn', $order_sn)->where('goods_id', $goods_id)->first();

        if(!empty($isHas)){

            $return['status'] = 0;

            $return['message'] = "该商品已经申请过售后";

            return $return;
        }


        $orders = Order::where('order_sn', $order_sn)->first();

        $order_id = $orders->order_id;

        $mobile = $orders->mobile;

        if(trim($phone) !== trim($mobile)){

            $return['status'] = 0;

            $return['message'] = "手机号必须跟下单时所用一样";

            return $return;
        }//end if()


        $order_goods = OrderGoods::where('order_id', $order_id)->where('goods_id', $goods_id)->first();

        $goods_sn = $order_goods->goods_sn;

        $order_goods_id = $order_goods->id;

        $shop_price = $order_goods->shop_price;

        $goods_real_price = $order_goods->goods_real_price;


        try{

            $refund_id = $refundGoodsService->createReturnGoods($user_id, $order_sn, $goods_id, $order_goods_id, $goods_sn, $after_sales_number, $real_name, $phone, $shop_price, $goods_real_price, $reason, $remark, $refundGoodsOperationRecordService);

            $return['data'] = $refund_id;

            $refund_sn = RefundGoods::where('refund_id', $refund_id)->pluck('refund_sn');

            $this->dispatch(
                new OperationLogCommand('用户申请售后', 'refund_goods','refund_id:'.$refund_id.';order_id:'.$order_id.';goods_id:'.$goods_id)
            );

            // return Redirect('my/refund/'.$refund_sn);
            $return['data'] = 'my/refund/'.$refund_sn;

        } catch (RefundGoodsServiceException $e) {

            $return['status'] = 0;

            $return['message'] = $e->getMessage();
        }//end try

        return $return;
    }//end func create()

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * 售后（退款）详情页
     *
     * @param  string  $refund_sn       售后服务单号
     *
     * @return \Illuminate\Http\Response
     */
    public function show($refund_sn)
    {

        $return = ['status'=>1, 'message'=>'', 'data'=>''];

        $refund_goods = RefundGoods::where('refund_sn', $refund_sn)->first();


        if($refund_goods){

            return view('front.my.refund_goods_detail', compact(['refund_goods']));         //商品退货详情页
        }

    }//end func show()

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * 取消售后申请
     *
     * @param  string  $refund_sn       售后服务单号
     * @param  App\Interfaces\RefundGoodsService  $refundGoodsService       售后（退货）服务
     *
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $refund_sn, RefundGoodsService $refundGoodsService)
    {
        $return = ['status'=>1, 'message'=>'', 'data'=>''];

        $refund_sn = 'G2187761227534d';
        //$refund_sn = '';
        $refund_status = 5;         //售后服务状态：1:待确认; 2:已受理；3:处理完毕；4:不予受理；5:已取消；
        $real_name = 'Leen';
        $phone = 15136168236;
        $remark = '修改备注';
        $user_id = Auth::user()->id;

        try{

//todo 增加用户要取消的售后申请是否是该用户的

            $refundGoodsService->updateReturnGoods($user_id, $refund_sn, $refund_status, $real_name, $phone, $remark);

        } catch (RefundGoodsServiceException $e) {

            $return['status'] = 0;
            $return['message'] = $e->getMessage();

        }//end try

        return $return;
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }

    /**
     * 售后（退货）申请页面
     *
     * @param  string  $refund_sn       售后服务单号
     * @param  App\Interfaces\RefundGoodsService  $refundGoodsService       售后（退货）服务
     *
     * @return \Illuminate\Http\Response
     */
    public function apply($order_sn, $goods_id,Request $request)
    {
        $return = ['status'=>1, 'message'=>'', 'data'=>''];
        $afterSalesTypeArr = ['1'=>'退货'];

        //dd('refund applay');
        $order_id = Order::where('order_sn',$order_sn)->pluck('order_id');
        $orders = Order::findOrNew($order_id);

        $order_goods = OrderGoods::where('order_id',$order_id)->where('goods_id', $goods_id)->first();

        if($order_goods){

            return view('front.my.refund_goods_apply', compact(['order_goods', 'orders', 'afterSalesTypeArr']));        //商品退货申请页面
        }else{
            //订单商品不存在
        }//end if()

    }

    /**
     * 售后（退货）商品记录
     *
     * @param  string  $refund_sn       售后服务单号
     * @param  App\Interfaces\RefundGoodsService  $refundGoodsService       售后（退货）服务
     *
     * @return \Illuminate\Http\Response
     */
    public function record(Request $request)
    {
        $query = RefundGoods::orderBy('refund_id', 'desc')
            ->where('user_id', $this->user_id);

        $search = array('condition'=>'', 'refund_status'=>'');
        $refundStatusArr = ['-1'=>'全部状态', '0'=>'待确认', '1'=>'已受理', '2'=>'处理完毕', '3'=>'不予受理', '4'=>'已取消'];

        if ($request->condition!=''){
            $query = $query->whereRaw("(order_sn like '%$request->condition%' or refund_sn like '%$request->condition%')");

            $search['condition'] = $request->condition;
        }//end if()

        /*if ($request->refund_sn!=''){
            $query = $query->where('refund_sn', $request->refund_sn);
            $search['refund_sn'] = $request->refund_sn;
        }//end if()*/

        if ($request->refund_status!=''){
            $query = $query->where('refund_status', $request->refund_status);
            $search['refund_status'] = $request->refund_status;
        }//end if()

        $refundOrders = $query->paginate(10);         //结果没有软删除的订单

        return view('front.my.refund_goods_record', compact(['refundOrders', 'search', 'refundStatusArr']));         //商品退货记录列表
    }

    /**
     * 售后（退款）明细
     *
     * @param  string  $refund_sn       售后服务单号
     * @param  App\Interfaces\RefundGoodsService  $refundGoodsService       售后（退货）服务
     *
     * @return \Illuminate\Http\Response
     */
    public function detail(Request $request)
    {
        $return = ['status'=>1, 'message'=>'', 'data'=>''];


        return view('front.my.refund_goods_detail_list');         //商品退货明细列表
    }


}
